package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;


    /**
     * 微信小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public Result login(UserLoginDTO dto) {
        if (dto.getCode() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //设置url地址
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        //设置参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        //设置请求头
        String body = HttpClientUtil.doGet(url, paramMap);
        //将请求头转换格式
        Map map = JSONObject.parseObject(body, Map.class);
        if (map == null || map.size() == 0) {
            return Result.error(MessageConstant.LOGIN_FAILED);
        }
        //获取登录之后的唯一标识
        String openid = (String) map.get("openid");
        //根据openid去获取uesr表，如果没有数据，则注册
        User user = userMapper.getByOpenId(openid);
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.addUser(user);
        }
        //封装数据返回
        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(JwtUtil.getToken(user.getId()))
                .build();

        return Result.success(vo);
    }
}
